package com.timanetworks.audi.vehicle.remind;

import freemarker.core.ParseException;
import freemarker.template.MalformedTemplateNameException;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import freemarker.template.TemplateNotFoundException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import java.io.IOException;
import java.time.LocalDate;
import java.time.LocalTime;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;


//            <dependency>
//                <groupId>org.springframework.boot</groupId>
//                <artifactId>spring-boot-starter-freemarker</artifactId>
//                <version>2.0.3.RELEASE</version>
//            </dependency>
//        <dependency>
//                <groupId>javax.mail</groupId>
//                <artifactId>mail</artifactId>
//                <version>1.4.7</version>
//                </dependency>


/**
 * Created by wusk on 2017/10/12.
 */
@Service
public class AlarmRemindMailSendService {
    private static final Logger logger = LoggerFactory.getLogger(AlarmRemindMailSendService.class);

    private static final String MAIL_TEMPLATE_FILE_NAME = "alarm-mail-remind.ftl";

    //注入MailSender
    @Autowired
    private JavaMailSender mailSender;

    //发送邮件的模板引擎
    @Autowired
    private FreeMarkerConfigurer configurer;

//    @Value("${service.mail.server.host}")
//    private String host;
//
//    @Value("${service.mail.user.name}")
//    private String uname;
//
//    @Value("${service.mail.user.password}")
//    private String password;

    @Value("${spring.mail.from}")
    private String from;

//    private Session session;

//    public void init(){
//        Properties properties = new Properties();
//        properties.setProperty("mail.smtp.auth", "true");//必须 普通客户端
//        properties.setProperty("mail.transport.protocol", "smtp");//必须选择协议
//        properties.setProperty("mail.host", host);
//        properties.setProperty("mail.debug", "false");
//
//        session = Session.getDefaultInstance(properties);
//        logger.info("Mail session has initialize. host = {}", host);
//    }

//    /**
//     * 发送简单文本邮件
//     * @param target  收件人
//     * @param subject 邮件主题
//     * @param content 邮件内容（不包含图片，附件等）
//     */
//    public void send(String target, String subject, String content){
//        if(null == session){
//            init();
//        }
//        Message message = new MimeMessage(session);
//        try{
//            //发件人
//            message.setFrom(new InternetAddress(from));
//            //主题
//            message.setSubject(subject);
//            //收件人
//            message.setRecipients(MimeMessage.RecipientType.TO, InternetAddress.parse(target));
//            //设置抄送自己
//            message.setRecipients(MimeMessage.RecipientType.CC, InternetAddress.parse(from));
//            //邮件内容
//            message.setContent(content, "text/html;charset=gbk");
//
//            Transport transport = session.getTransport();
//            transport.connect(uname, password);
//            transport.sendMessage(message, message.getAllRecipients());
//            transport.close();
//            logger.info("Send mail successfully. mail subject = {}, mail receivers = {}", subject, target);
//        }catch (Exception e){
//            logger.error("Send mail fail. mail subject = {}, mail receivers = {}", subject, target);
//            logger.error("", e);
//        }
//    }
//
//    /**
//     * 发送复杂邮件
//     * @param target  收件人
//     * @param subject 邮件主题
//     * @param body 邮件内容关系描述（包含图片，附件等）
//     */
//    public void send(String target, String subject, MimeMultipart body){
//        if(null == session){
//            init();
//        }
//        Message message = new MimeMessage(session);
//        try{
//            //发件人
//            message.setFrom(new InternetAddress(from));
//            //主题
//            message.setSubject(subject);
//            //收件人
//            message.setRecipients(MimeMessage.RecipientType.TO, InternetAddress.parse(target));
//            //设置抄送自己
//            message.setRecipients(MimeMessage.RecipientType.CC, InternetAddress.parse(from));
//            //邮件内容
//            message.setContent(body);
//
//            Transport transport = session.getTransport();
//            transport.connect(uname, password);
//            transport.sendMessage(message, message.getAllRecipients());
//            transport.close();
//            logger.info("Send mail successfully. mail subject = {}, mail receivers = {}", subject, target);
//        }catch (Exception e){
//            logger.error("Send mail fail. mail subject = {}, mail receivers = {}", subject, target);
//            logger.error("", e);
//        }
//    }

    public void send(String receiver, String subject, Map<String, Object> data){
        try {

            MimeMessage mimeMessage = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
            helper.setFrom(from);//发送者
            helper.setTo(InternetAddress.parse(receiver));//发送给谁

            helper.setSubject(subject);//邮件标题
            Template template = configurer.getConfiguration().getTemplate(MAIL_TEMPLATE_FILE_NAME);
            String text = FreeMarkerTemplateUtils.processTemplateIntoString(template, data);

            helper.setText(text, true);
            mailSender.send(mimeMessage);
        } catch (Exception e) {
            logger.error("Send mail to {} fail. data = {}", receiver, data);
            logger.error("", e);
        }
    }
}
